package net.bcxuexi.server.stream.inhandle;

import net.bcxuexi.config.Config;
import net.bcxuexi.exception.MyException;
import net.bcxuexi.ports.model.IPort;
import net.bcxuexi.server.ServerSocketManager;
import net.bcxuexi.server.SocketManager;
import net.bcxuexi.server.model.SocketModel;
import net.bcxuexi.server.stream.StreamData;
import net.bcxuexi.server.stream.outwrap.OutputDataWrap;
import net.bcxuexi.tools.MyLog;
import net.bcxuexi.tools.StringUtils;

/**
 * 代理连接输入流数据处理
 */
public class ProxyInputStreamHandler extends AbstractInputStreamHandler {

	public ProxyInputStreamHandler() {
	}

	@Override
	public void handle() {
		StreamData streamData = null;// 待处理数据

		if (streamData == null) {
			try {
				streamData = take();// 从阻塞队列中取数据，可能会被阻塞
			} catch (InterruptedException e) {
				// 没有取到数据
				return;
			}
		}

		if (streamData == null) {
			MyLog.info("ProxyInputStreamHandler队列为空，休息！");
			return;
		}
		// 数据处理
		process(streamData);
		try {
			sleep(80);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 数据信息封装，添加头部再发送数据给客户端。 需要验证数据通信socket
	 * 
	 * @param streamData
	 */
	public void process(StreamData streamData) {
		
		// 查找当前代理socket对应的data通信socket
		int proxyPort = streamData.getSocketModel().getServerSocketModel().getPort();
		String connId = streamData.getSocketModel().getConnId();

		SocketModel dataSocketModel = SocketManager.getInstance().findDataSocketByProxyConnId(connId);
		
		if (dataSocketModel == null || !dataSocketModel.getHasValidConnId()) {
			MyLog.info("数据通信未建立，无法传输数据");
			return;
		}
		if (!dataSocketModel.isActive()) {
			MyLog.info("数据通信已关闭，无法传输数据");
			return;
		}
		streamData.getSocketModel().setClientkey(dataSocketModel.getClientkey());
		//查找iport
		IPort iport = ServerSocketManager.getInstance().findIportByProxy(proxyPort);
		if(iport==null){
			MyLog.info("未找到代理端口对应的iport。代理端口："+proxyPort);
			return;
		}
		if(StringUtils.isBlack(iport.getIp())&&iport.getPort()<=0){
			MyLog.info("iport无效");
			return;
		}
		try {
			//封装消息
			OutputDataWrap outputDataWrap = new OutputDataWrap();
			StreamData dataStreamData = outputDataWrap.scDataWrap(streamData,
					streamData.getSocketModel().getConnId(),
					iport.getIp(), iport.getPort());
			dataStreamData.setSocketModel(dataSocketModel);
			System.out.println("发送data数据.proxyConnId="+dataStreamData.getProxyConnId()+".data connId="+dataSocketModel.getConnId());
			if(Config.debug){
				String wdata = new String(dataStreamData.data,0,dataStreamData.total);
				MyLog.info("代理信息添加头部后的数据："+wdata);
			}
			try {
				//发送消息
				dataSocketModel.getWriteStream().addData(dataStreamData);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (MyException e) {
			MyLog.info(e.msg);
		}
	}

}
